package cn.lingyangwl.agile.model;

import cn.lingyangwl.agile.model.constants.DataRuleCons;
import cn.lingyangwl.agile.model.module.perm.DataRuleContext;
import cn.lingyangwl.agile.model.module.perm.DataRuleContextHolder;
import cn.lingyangwl.framework.mybatis.mate.inter.EntityFieldUniqueCheck;
import cn.lingyangwl.framework.tool.core.StringUtils;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 持久化对象的基类
 *
 * @author shenguangyang
 */
public class BasePO implements Serializable, EntityFieldUniqueCheck {
    private static final Logger log = LoggerFactory.getLogger(BasePO.class);
    private static final long serialVersionUID = 1L;

    public static final String HAS_DATA_RULE_SQL = "hasDataRuleSql";
    public static final String DATA_RULE_SQL = "dataRuleSql";

    /**
     * 请求参数
     */
    @TableField(exist = false)
    @JsonIgnore
    private Map<String, Object> params = new HashMap<>();

    public Map<String, Object> getParams() {
        params.put(HAS_DATA_RULE_SQL, Boolean.FALSE);

        DataRuleContext appContext = DataRuleContextHolder.get();
        if (Objects.isNull(appContext)) {
            return params;
        }
        if (StringUtils.isEmpty(appContext.getDataScopeSql())) {
            params.put(DataRuleCons.DATA_SCOPE, "");
        } else {
            params.put(DataRuleCons.DATA_SCOPE, appContext.getDataScopeSql());
            // log.debug("data scope is {} ", appContext.getDataScopeSql());
        }

        // 判断是否有数据规则sql
        if (StringUtils.isNotEmpty(appContext.getDataRuleSql())) {
            params.put(HAS_DATA_RULE_SQL, Boolean.TRUE);
            params.put(DATA_RULE_SQL, appContext.getDataRuleSql());
        }
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

    public void addExt(String key, Object value) {
        this.params.put(key, value);
    }
}
